package com.example.leoss.duanxingxufa;

import android.content.SharedPreferences;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.SearchView;
import android.telephony.SmsManager;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.leoss.R;
import com.example.leoss.duanxingxufa.SQliteMsg.Caozuo2;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class SendActivity extends AppCompatActivity implements SearchView.OnQueryTextListener, View.OnClickListener {
    String SENT_SMS_ACTION = "SENT_SMS_ACTION";
    String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
    public static final Uri SMS_URI = Uri.parse("content://sms/");
    public Button button;
    public  int h=0,is=8;

    private String body;//短信内容
    private SearchView id_duanxinQF_search1s;
    private ListView id_message_lv1s;
    SharedPreferences sharedPreferences;
    private TextView id_layout_msg_tv_content1s;
    private TextView id_layout_msg_tv_phone1s;
    private  ImageView img_yifasong;
    private  TextView name;
    ArrayList<String> phone_num = new ArrayList<String>();
    long id;
    View dialogView;
    Set<String> addr;

    String list_content;
    String list_phone;
    String list_name;
    private ArrayList<DataDx> list;
    private ArrayList<DataDx> mListSearch;
    private boolean insi;
    private LinearLayout mLlEditBar;//控制下方那一行的显示与隐藏
    private List<DataDx> mCheckedData = new ArrayList<>();//将选中数据放入里面
    private SparseBooleanArray stateCheckedMap = new SparseBooleanArray();//用来存放CheckBox的选中状态，true为选中,false为没有选中
    private SparseBooleanArray stateImage = new SparseBooleanArray();
    private boolean isSelectedAll = true;//用来控制点击全选，全选和全不选相互切换

    DxAdpate dxAdpate;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send);

        sharedPreferences= getSharedPreferences("data",Context.MODE_PRIVATE);

        initView();
        message_show();
        setStateImage(false);
        setTitle("短信群发");

        //setStateImage(false);

        setOnListViewItemClickListener();
        setOnListViewItemLongClickListener();
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.ll_cancel:
                cancel();
                break;
            case R.id.ll_delete:
                delete();
                break;
            case R.id.ll_inverse:
                inverse();
                break;
            case R.id.ll_select_all:
                selectAll();
                break;
        }
    }


    private void delete() {
        if (mCheckedData.size() == 0) {
            Toast.makeText(SendActivity.this, "您还没有选中任何数据！", Toast.LENGTH_SHORT).show();
            return;
        }
        final CustomDialog dialog = new CustomDialog(this);
        dialog.show();
        dialog.setHintText("是否删除？");
        dialog.setLeftButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setRightButton("确定", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                beSureDelete();
                dialog.dismiss();
            }
        });
    }

    private void beSureDelete() {
        list.removeAll(mCheckedData);//删除选中数据
        setStateCheckedMap(false);//将CheckBox的所有选中状态变成未选中
        mCheckedData.clear();//清空选中数据
        dxAdpate.notifyDataSetChanged();
        Toast.makeText(SendActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
    }
    /**
     * 反选就是stateCheckedMap的值为true时变为false,false时变成true
     * */
    private void inverse() {
        mCheckedData.clear();
        for (int i = 0; i < list.size(); i++) {
            if (stateCheckedMap.get(i)) {
                stateCheckedMap.put(i, false);
            }
            else {
                stateCheckedMap.put(i, true);
                mCheckedData.add(list.get(i));
            }
            id_message_lv1s.setItemChecked(i, stateCheckedMap.get(i));//这个好行可以控制ListView复用的问题，不设置这个会出现点击一个会选中多个
        }
        dxAdpate.notifyDataSetChanged();
    }

    private void selectAll() {
        mCheckedData.clear();//清空之前选中数据
        if (isSelectedAll) {
            setStateCheckedMap(true);//将CheckBox的所有选中状态变成选中
            isSelectedAll = false;
            mCheckedData.addAll(list);//把所有的数据添加到选中列表中
        } else {
            setStateCheckedMap(false);//将CheckBox的所有选中状态变成未选中
            isSelectedAll = true;
        }
        dxAdpate.notifyDataSetChanged();
    }

    private int posi;
    private void setOnListViewItemClickListener() {

        id_message_lv1s.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


                if (dxAdpate.isShowCheckBox()){


                    updateCheckBoxStatus(view, position);

                    //id_message_lv1s.setItemChecked(position);

                }else {
                    stateImage.put(position, true);
                    id_layout_msg_tv_phone1s = view.findViewById(R.id.id_layout_msg_tv_phone);
                    list_phone = id_layout_msg_tv_phone1s.getText().toString();//phome
                    id_layout_msg_tv_content1s = view.findViewById(R.id.id_layout_msg_tv_content);
                    list_content = id_layout_msg_tv_content1s.getText().toString();//信息
                    name = view.findViewById(R.id.id_layout_msg_tv_name); //姓名
                    list_name = list.get(position).getName();
                    img_yifasong = view.findViewById(R.id.img_yifasong);

                    // Toast.makeText(SendActivity.this, list_phone, Toast.LENGTH_SHORT).show();

                    for (int num = 0; num <= phone_num.size(); num++)
                    {
                        Toast.makeText(SendActivity.this, phone_num.toString(), Toast.LENGTH_SHORT).show();

                        if ((!phone_num.contains(String.valueOf(position))))
                        {
                            if(ContextCompat.checkSelfPermission(SendActivity.this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED)
                            {
                                ActivityCompat.requestPermissions(SendActivity.this, new String[]{Manifest.permission.SEND_SMS}, 3);
                            } else
                            if(ContextCompat.checkSelfPermission(SendActivity.this , Manifest.permission.READ_PHONE_STATE)!=PackageManager.PERMISSION_GRANTED)
                            {
                                ActivityCompat.requestPermissions(SendActivity.this,new String[]{Manifest.permission.READ_PHONE_STATE},4);
                            }
                            phone_num.add(String.valueOf(position));
                        }else {
                            Toast.makeText(SendActivity.this, "已经发送", Toast.LENGTH_SHORT).show();
                        }
                    }


                }
            }
        });
    }


    private void updateCheckBoxStatus(View view, int position) {

        DxAdpate.ViewHolder holder = (DxAdpate.ViewHolder) view.getTag();
        holder.checkBox.toggle();//反转CheckBox的选中状态
        id_message_lv1s.setItemChecked(position, holder.checkBox.isChecked());//长按ListView时选中按的那一项
        stateCheckedMap.put(position, holder.checkBox.isChecked());//存放CheckBox的选中状态

        if (holder.checkBox.isChecked()) {
            mCheckedData.add(list.get(position));//CheckBox选中时，把这一项的数据加到选中数据列表
        } else {
            mCheckedData.remove(list.get(position));//CheckBox未选中时，把这一项的数据从选中数据列表移除
        }
        dxAdpate.notifyDataSetChanged();
    }

    /**
     * 如果返回false那么click仍然会被调用,,先调用Long click，然后调用click。
     * 如果返回true那么click就会被吃掉，click就不会再被调用了
     * 在这里click即setOnItemClickListener
     */
    private void setOnListViewItemLongClickListener() {

        id_message_lv1s.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

                if (button.getText().equals("隐藏")){
                    mLlEditBar.setVisibility(View.GONE);//显示下方布局
                    dxAdpate.setShowCheckBox(false);//CheckBox的那个方框显示
                }else {
                    mLlEditBar.setVisibility(View.VISIBLE);//显示下方布局
                    dxAdpate.setShowCheckBox(true);//CheckBox的那个方框显示
                    updateCheckBoxStatus(view, position);
                }

                return true;
            }
        });
    }
    /**
     * 设置所有CheckBox的选中状态
     * */
    private void setStateCheckedMap(boolean isSelectedAll) {

        for (int i = 0; i < list.size(); i++) {
            stateCheckedMap.put(i, isSelectedAll);
            id_message_lv1s.setItemChecked(i, isSelectedAll);
        }
    }

    private  void  setStateImage(boolean isImage){
        for (int i = 0; i < list.size(); i++) {
            stateImage.put(i, isImage);
         //   id_message_lv1s.setItemChecked();
          // id_message_lv1s.setItemChecked(i, isImage);
        }
    }

    @Override
    public void onBackPressed() {
        if (mLlEditBar.getVisibility() == View.VISIBLE) {
            cancel();
            return;
        }
        super.onBackPressed();
    }

    private void cancel() {
        setStateCheckedMap(false);//将CheckBox的所有选中状态变成未选中
        mLlEditBar.setVisibility(View.GONE);//隐藏下方布局
        dxAdpate.setShowCheckBox(false);//让CheckBox那个方框隐藏
        dxAdpate.notifyDataSetChanged();//更新ListView
    }
    /**
     * Listview 显示
     */
    private void message_show()
    {


        list = new ArrayList<>();
        Caozuo2 caozuo=new Caozuo2(this);
        Cursor mCursor = caozuo.xianshi();



        while (mCursor.moveToNext())
        {   String id=mCursor.getString(0);
            String name=mCursor.getString(1);//id
            String  phome= mCursor .getString(2);
            String content=mCursor.getString(3);

                list.add(new DataDx(id,name ,phome,content,SendActivity.this));
        }

       dxAdpate=new DxAdpate(list,SendActivity.this,stateCheckedMap,stateImage);
        id_message_lv1s.setAdapter(dxAdpate);

//        /*
//           Listview 事件监听
//         */
//        id_message_lv1s.setOnItemClickListener(new AdapterView.OnItemClickListener()
//        {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
//            {
//
//
//
//            }
//        });

        id_message_lv1s.setTextFilterEnabled(true);
        id_duanxinQF_search1s.setIconifiedByDefault(false);
        id_duanxinQF_search1s.setOnQueryTextListener(this);
        id_duanxinQF_search1s.setSubmitButtonEnabled(false);
    }
    /*
    初始化
    */
    private void initView()
    {


        id_message_lv1s = (ListView) findViewById(R.id.id_message_lv);
        button=findViewById(R.id.xianshi_send_dx1);
        mLlEditBar = findViewById(R.id.ll_edit_bar);

        findViewById(R.id.ll_cancel).setOnClickListener(this);
        findViewById(R.id.ll_delete).setOnClickListener(this);
        findViewById(R.id.ll_inverse).setOnClickListener(this);
        findViewById(R.id.ll_select_all).setOnClickListener(this);
        id_message_lv1s.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

        id_duanxinQF_search1s=findViewById(R.id.id_duanxingQF_search);

        if (button.getText().equals("显示详情"))
        {
            is=0;
            h=50;
            insi=false;
            button.setText("隐藏");
            //步骤2： 实例化SharedPreferences.Editor对象
            SharedPreferences.Editor editor = sharedPreferences.edit();
            //步骤3：将获取过来的值放入文件
            editor.putInt("h",h);
            editor.putInt("is",is);
            editor.putBoolean("src",true);
            editor.putBoolean("boolea",true);
            //步骤4：提交
            editor.commit();
            message_show();
        }else {

            is=8;
            h=0;
            insi=true;
            button.setText("显示详情");
            //步骤2： 实例化SharedPreferences.Editor对象
            SharedPreferences.Editor editor = sharedPreferences.edit();
            //步骤3：将获取过来的值放入文件
            editor.putInt("h",h);
            editor.putInt("is",is);
            editor.putBoolean("src",false);
            //步骤4：提交
            editor.commit();
            message_show();
        }


/**
 * Listview 显示详情页
 */
        button.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
//                Toast.makeText(SendActivity.this,"Button",Toast.LENGTH_SHORT).show();

                if (button.getText().equals("显示详情"))
                {       mLlEditBar.setVisibility(View.GONE);//显示下方布局
                    is=0;
                    h=50;
                    insi=false;
                    button.setText("隐藏");
                    //步骤2： 实例化SharedPreferences.Editor对象
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    //步骤3：将获取过来的值放入文件
                    editor.putInt("h",h);
                    editor.putInt("is",is);
                    editor.putBoolean("src",true);
                    editor.putBoolean("boolea",true);
                    //步骤4：提交
                    editor.commit();
                    message_show();
                }else {

                    is=8;
                    h=0;
                    insi=true;
                    button.setText("显示详情");
                    //步骤2： 实例化SharedPreferences.Editor对象
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    //步骤3：将获取过来的值放入文件
                    editor.putInt("h",h);
                    editor.putInt("is",is);
                    editor.putBoolean("src",false);
                    //步骤4：提交
                    editor.commit();
                    message_show();

                }

            }
        });



    }

    public void sendSMS(Set<String> phone, String body, long threadId)
    {
        SmsManager msg = SmsManager.getDefault();
        Intent send = new Intent(SENT_SMS_ACTION);
        // 短信发送广播
        PendingIntent sendPI = PendingIntent.getBroadcast(
                this, 0, send, 0);
        Intent delive = new Intent(DELIVERED_SMS_ACTION);
        // 发送结果广播
        PendingIntent deliverPI = PendingIntent.getBroadcast(
                this, 0, delive, 0);
        //将数据插入数据库·
        ContentValues cv = new ContentValues();

        for(String pno:phone )
        {
            msg.sendTextMessage(pno, null, body, sendPI, deliverPI);
            cv.put("thread_id", threadId);
            cv.put("date", System.currentTimeMillis());
            cv.put("body", body);
            cv.put("read", 0);
            cv.put("type", 2);
            cv.put("address", pno);
            this.getContentResolver().insert(SMS_URI, cv);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
    {
        switch(requestCode)
        {
            case 1:
                if(grantResults.length > 0 && grantResults[0]== PackageManager.PERMISSION_GRANTED){
                    sendSMS(addr, body, id);
                } else {
                    Toast.makeText(this,"发送成功！",Toast.LENGTH_SHORT).show();
                }
                break;
            case 2:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    sendSMS(addr, body, id);
                } else {
                    sendSMS(addr, body, id);
                    Toast.makeText(this,"Success!",Toast.LENGTH_SHORT).show();
                }
            case 3:
                if(grantResults.length > 0 && grantResults[0]== PackageManager.PERMISSION_GRANTED){
                    sendSingalMsg(list_phone,list_content);
                } else {
                    Toast.makeText(this,"发送成功！",Toast.LENGTH_SHORT).show();
//                    Toast.makeText(this,"抱歉您没有此权限！",Toast.LENGTH_SHORT).show();
                }
                break;
            case 4:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    sendSingalMsg(list_phone,list_content);
                } else {
                    sendSingalMsg(list_phone,list_content);
                    id_layout_msg_tv_content1s.setBackgroundColor(Color.RED);
//                    Toast.makeText(this,"Success!",Toast.LENGTH_SHORT).show();
                }
            default:
        }
    }

    private void sendSingalMsg(String phone, String content)
    {

        try{

            if (TextUtils.isEmpty(phone)) {
                Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();

            }
            if (TextUtils.isEmpty(content)) {
                Toast.makeText(this, "请输入内容", Toast.LENGTH_SHORT).show();

            }
            ArrayList<String> messages = SmsManager.getDefault().divideMessage(content);

              SmsManager.getDefault().sendMultipartTextMessage(phone, null, messages, null, null);
              Toast.makeText(this, list_name+"发送完成", Toast.LENGTH_SHORT).show();
              img_yifasong.setVisibility(View.VISIBLE);


        } catch (SecurityException e)
        {
            e.printStackTrace();
        }
    }


    protected void onResume()
    {
        super.onResume();
        //注册监听
        registerReceiver(sendMessage, new IntentFilter(SENT_SMS_ACTION));
    }

    BroadcastReceiver sendMessage = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context c, Intent intent)
        {
            // 判断短信是否成功
            switch (getResultCode())
            {
                case Activity.RESULT_OK:
                    Toast.makeText(SendActivity.this, "发送成功！", Toast.LENGTH_SHORT)
                            .show();
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE://普通错误
                    Toast.makeText(SendActivity.this, "短信发送失败！", Toast.LENGTH_SHORT);
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    Toast.makeText(SendActivity.this, "服务当前不可用！", Toast.LENGTH_SHORT);
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    Toast.makeText(SendActivity.this, "没有提供pdu！", Toast.LENGTH_SHORT);
                    break;

                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    Toast.makeText(SendActivity.this, "无线广播被明确地关闭！", Toast.LENGTH_SHORT);
                    break;
                default:
                    Toast.makeText(SendActivity.this, "发送失败！", Toast.LENGTH_SHORT)
                            .show();
                    break;
            }
        }
    };



    @Override
    public boolean onQueryTextSubmit(String query) {
        if (id_duanxinQF_search1s != null)
        {
            // 得到输入管理对象
            InputMethodManager imm = (InputMethodManager)SendActivity.this.getSystemService(SendActivity.this.INPUT_METHOD_SERVICE);
            if (imm != null) {
                // 这将让键盘在所有的情况下都被隐藏
                imm.hideSoftInputFromWindow(id_duanxinQF_search1s.getWindowToken(), 0); // 输入法如果是显示状态，那么就隐藏输入法
            }else {
                id_duanxinQF_search1s.getImeOptions();
            }
            id_duanxinQF_search1s.clearFocus(); // 不获取焦点
        }
        return false;
    }

    @Override
    public boolean onQueryTextChange(String s)
    {

        //    int st=Integer.parseInt(s);
        if (!TextUtils.isEmpty(s))
        {
            String text = s.toString().trim();
            mListSearch=new ArrayList<>();
            if (!TextUtils.isEmpty(text))
            {
                if (mListSearch != null && mListSearch.size() > 0) {
                    // mListSearch 模糊搜索结果集合
                    mListSearch.clear();
                }
                // mList 需要模糊搜索的集合
                for (DataDx bean : list) {
                    // 判断javabean中是否包含搜索字段
                    if (bean.getName().contains(text)||bean.getPhome().contains(text)||bean.getId().contains(s)) {
                        // 若包含，添加
                        mListSearch.add(bean);
                    }
                }
                // 给RecycleView设置搜索结果
                dxAdpate= new DxAdpate(mListSearch,SendActivity.this,stateCheckedMap,stateImage);
                id_message_lv1s.setAdapter(dxAdpate);
            }
        } else {
            // 输入框输入字段为空
            mListSearch.clear();
            dxAdpate = new DxAdpate(list,SendActivity.this,stateCheckedMap,stateImage);
            id_message_lv1s.setAdapter(dxAdpate);
        }

        return true;
    }


}
